package com.tencent.wxcloudrun.service.business;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tencent.wxcloudrun.config.UserContext;
import com.tencent.wxcloudrun.pojo.po.XPersonInfo;
import com.tencent.wxcloudrun.service.XPersonInfoService;
import com.tencent.wxcloudrun.service.business.fangdong.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class CommonService {

    @Resource
    private PersonService personService;

    @Resource
    private XPersonInfoService xPersonInfoService;

    @Transactional(rollbackFor = Exception.class)
    public String justOpen() {
        String openId = UserContext.getOpenId();
        log.info(">>>>>> 发现用户登入，当前用户的openId是 {}", openId);
        Date date = new Date();
        LambdaQueryWrapper<XPersonInfo> xPersonInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        xPersonInfoLambdaQueryWrapper.eq(XPersonInfo::getPersonId, openId);
        List<XPersonInfo> allList = xPersonInfoService.list(xPersonInfoLambdaQueryWrapper);
        if (CollUtil.isEmpty(allList)) {
            log.info(">>>>>> 发现当前用户是首次打开此小程序，准备将其设置为租客角色。");
            XPersonInfo xPersonInfo = new XPersonInfo();
            xPersonInfo.setPersonId(openId);
            xPersonInfo.setPersonType("tenant");
            xPersonInfo.setCreateTime(date);
            xPersonInfo.setUpdateTime(date);
            xPersonInfoService.save(xPersonInfo);
            log.info(">>>>>> 首次使用小程序的用户成功注册基础信息，返回tenant字段让前端进行页面跳转。");
            return "tenant";
        }
        String landlord = personService.isLandlord();
        if ("yes".equals(landlord)) {
            return "landlord";
        }
        return "tenant";
    }
}
